var data1 = [{'id':'1','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'完成箱'},{'id':'2','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'垃圾箱'},
    {'id':'3','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'待批箱'},{'id':'4','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'草稿箱'},
    {'id':'5','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'已批箱'},{'id':'6','receiptno':'text1','cdate':'text2','operation':'text3','warehousepeople':'text4','warehousename':'text5','note':'text6','documenttype':'草稿箱'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
var isMsn="否";
let isContainsRole=false;
getIsContainsRole();

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        initValue:[user.code],
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


let operationList=[];
let salesmanList=[];
let deptOperationList=[];
let deptSalesmanList=[];
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCodeStr", userTree);
        salesmanList=getxmselect("#salesmanCode","salesmanCodeStr", userTree);
    }else {
        operationList=getxmselect("#operationCode","operationCodeStr", [{name: user.name, value: user.code}]);
        salesmanList=getxmselect("#salesmanCode","salesmanCodeStr", [{name: user.name, value: user.code}]);
    }
    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

    //获取目的地/国家信息
    $.ajax({
        url:"offer/getCountry",
        success:function(data){
            if(data.status == 200){
                for (let i in data.data) {
                    $('#destinationCode').append(new Option(data.data[i].name, data.data[i].name));
                }
                form.render('select');
            }
        }
    });

})()

layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("customsdeclarationtableid");
        $.ajax({
            url: 'billDeclare/selectLogo?declare_id='+checkStatus.data[0].declareId,
            type: 'GET',
            async: false, // 同步
            success: function (date) {
            },
        });
        switch (event) {
            case "printfn1":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billdeclare&code=code:"+checkStatus.data[0].declareId)
                break
            case "printfn2":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billdeclare2&code=code:"+checkStatus.data[0].declareId)
                break
            case "printfn3":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billdeclare3&code=code:"+checkStatus.data[0].declareId)
                break
            case "printfn4":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billdeclare4&code=code:"+checkStatus.data[0].declareId)
                break
            case "printfn5":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个报关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的报关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billdeclare5&code=code:"+checkStatus.data[0].declareId)
                break
        }
    });
})

// layui.use(['selectM'], function () {
//     let selectM = layui.selectM;
//     //多选标签-基本配置
//     //所属操作员
//     let operation = getManageRule("BillDeclareOp");
//     let tagIns1 = selectM({
//         elem: '#operationCode'
//         ,data: operation
//         ,selected: [user.code]
//         ,width:202
//         ,field: {idName:'code',titleName:'name'}
//     });
//
//     let sm = getManageRule("BillDeclareSm");
//     //所属业务员
//     let tagIns2 = selectM({
//         elem: '#salesmanCode'
//         ,data: sm
//         ,width:202
//         ,field: {idName:'code',titleName:'name'}
//     });
//
//     //监听重置按钮
//     $('form').find(':reset').click(function(){
//         $('form')[0].reset();
//         tagIns1.set();
//         tagIns2.set();
//         return false;
//     });
// });

// function downLogo(url){
//     $.ajax({
//         url: 'ftp/onLine2?pathString='+url,
//         type: 'GET',
//         async: false, // 同步
//         success: function (date) {
//         },
//     });
// }

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

form.render();//表单刷新
table.render({
    elem: '#customsdeclarationselect'
    ,url: 'billDeclare/selectAllBillByPage'
    ,where:{operationCodeStr:user.code,salesmanCodeStr:user.code}
    ,toolbar: '#customsdeclarationtoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'billCustmsDeclareNo', title:'报关单号',sort:true,width: 120}
        ,{field:'invoiceNo', title:'报关发票号',sort:true,width: 120,event: "invoicenumber"}
        ,{field:'custName', title:'客户名称',sort:true,width: 120}
        ,{field:'customerLevelName', title:'客户级别',sort:true,width: 120}
        ,{field:'businessMode', title:'业务模式',sort:true,width: 120}
        ,{field:'companyName', title:'报关抬头 ',sort:true,width: 120}
        ,{field:'declarationDate', title:'报关日期',sort:true,width: 120}
        ,{field:'shippingDate', title:'出运日期',sort:true,width: 120}
        ,{field:'invoicemoney', title:'发票总额',sort:true,width: 120,hide:!isContainsRole}
        ,{field:'moneyName', title:'币种',sort:true,width: 120}
        ,{field:'createTime', title:'制单日期',sort:true,width: 120}
        ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'startplace', title:'起运地',sort:true,width: 120}
        ,{field:'endplace', title:'目的地',sort:true,width: 120}
        ,{field:'transMode', title:'运输方式',sort:true,width: 120}
        ,{field:'priceTerm', title:'价格术语',sort:true,width: 120}
        ,{field:'contractNo', title:'销售合同号',sort:true,width: 120}
        ,{field:'custContractNo', title:'客户合同号',sort:true,width: 120}
        ,{field:'atdDate', title:'实际开船日期ATD ',sort:true,width: 200}
        ,{field:'inStockDate', title:'进仓装柜日期 ',sort:true,width: 180}
        ,{field:'salesmanName', title:'业务员',sort:true,width: 120}
        ,{field:'bankName', title:'银行 ',sort:true,width: 120}
        ,{field:'opName', title:'操作员',sort:true,width: 120}
        ,{field:'whetherCreditGuarantee', title:'走信保订单',width: 120, templet: function(d){
                if(d.whetherCreditGuarantee==0){
                  return "否"
                }else if(d.whetherCreditGuarantee==1){
                    return "是(采购抬头：上海沣奇)"
                }else if(d.whetherCreditGuarantee==2){
                    return "是(采购抬头：上海源铢)"
                }else{
                    return ""
                }
        }}
        ,{field:'creditGuaranteeAmount', title:'信保订单金额USD',sort:true,width: 120}
        ,{field:'contact', title:'联系人',sort:true,width: 120}
        ,{field:'settleMode', title:'收款(结汇)方式',sort:true,width: 120}
        ,{fixed: 'right', width:240, title:'操作', templet: function(d){
                if(isMsn=="是"){
                    var html="<div>"
                    if(d.status==1 || d.status==2|| d.status==3){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                    }
                    if(d.status==1){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                    }
                    if(d.status==2 || d.status==3 ||d.status==4){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                    }
                    if(d.status==3){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                    }
                    if(d.status==1){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delete\">删除</a>"
                    }
                    if(d.status==5){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delectYes\">彻底删除</a><a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"reduction\">还原</a>"
                    }
                    return html+"</div>";
                }else {
                    var html = "<div>"
                    if (d.status == 1 || d.status == 2) {
                        html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                    }
                    if (d.status == 1) {
                        html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                    }
                    return html + "</div>";
                }
            }
        }
    ]]
    ,id: 'customsdeclarationtableid'
    ,height: $(document).height() - $('#customsdeclarationselect').offset().top - 50
    ,page: true
});
table.on('tool(customsdeclarationtable)', function(obj){
    var data = obj.data;
    var id=obj.data.declareId;
    if(obj.event === 'update') {
        parent.intab("views/jsp/ExportBusiness/tpl/newupcustomsdeclaration.jsp?id="+id,"修改报关")
    }else if(obj.event === 'delectYes'){
        layer.confirm('真的删除行么', function (index) {
            $.ajax({
                url: 'billDeclare/deleteBillById?billId='+id,
                type: 'GET',
                success: function (date) {
                }
            });
            obj.del();
            layer.close(index);
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            changeStatues(id,3)
            layer.msg('提交审批');
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            changeStatues(id,3)
            layer.msg('审批通过');
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            changeStatues(id,1)
            layer.msg('审批退回');
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            changeStatues(id,4)
            layer.msg('完成');
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            changeStatues(id,1)
            layer.msg('还原');
        });
    }else if(obj.event === 'delete'){
        layer.confirm('确定删除吗', function (index) {
            changeStatues(id,5)
            layer.msg('删除');
        });
    }else if (obj.event === "invoicenumber"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewcustomsdeclaration.jsp?id="+id,"报关明细")
    }
    form.render()
});

function changeStatues(id,statues){
    $.ajax({
        url: 'billDeclare/changeBillById?billId='+id+"&statues="+statues,
        type: 'GET',
        success: function (date) {
            table.reload("customsdeclarationtableid",{
                url: 'billDeclare/selectAllBillByPage'
            })

        }
    });
}
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
form.on('submit(submitform)', function(data){
    if (isEmpty(operationList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
        data.field.operationCodeStr=user.code;
        data.field.salesmanCodeStr=user.code;
    }
    table.reload('customsdeclarationtableid', {
        data:data1 ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where:data.field
    }, 'data');
    return false;
});
table.on('toolbar(customsdeclarationtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupcustomsdeclaration.jsp","新增报关")
            break;

    };

});

$("#statistical").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/statistics.jsp","报关统计")
});

$(document).ready(function () {
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
    $.ajax({
        url: 'billDeclare/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#company_code").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
            }
            form.render();
        }
    });
    // var op = getManageRule("BillDeclareOp");//操作员
    // for(let i in op){
    //     if(i==0){
    //         $("#op_code").append("<option selected   value='"+op[i].code+"'>"+op[i].name+"</option>")
    //     }else{
    //         $("#op_code").append("<option value='"+op[i].code+"'>"+op[i].name+"</option>")
    //     }
    // }
    // var sm = getManageRule("BillDeclareSm")//业务员
    //
    //     for(let i in sm){
    //
    //             $("#salesman_code").append("<option value='"+sm[i].code+"'>"+sm[i].name+"</option>")
    //
    // }

});


layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("costStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/customsdeclaration1.jsp","报关统计")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/foreignexchangesettlement2.jsp","报关xx统计")
                break
        }
    });
})

document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
};
function getIsContainsRole(){
    $.ajax({
        url: 'billDeclare/isContainsRole',
        async: false, // 同步
        success: function (data) {
            if (data.status==200){
                isContainsRole=data.data;
            }
        }
    });
}